package com.vj.router.client;

import com.vj.router.client.grpc.GrpcDeviceGatewayClient;

import java.util.Scanner;

public class RouterClientApplication {

    public static void main(String[] args) {
        System.out.println("Router Client is starting...");
        System.out.println("Commands: register, get, unregister, exit");

        // 初始化 gRPC 客户端
        GrpcDeviceGatewayClient grpcClient = new GrpcDeviceGatewayClient("localhost:9090");

        try (Scanner scanner = new Scanner(System.in)) {
            while (true) {
                System.out.print("Enter command: ");
                String command = scanner.nextLine().trim();

                switch (command.toLowerCase()) {
                    case "register":
                        System.out.print("Enter Device ID: ");
                        String deviceId = scanner.nextLine();
                        System.out.print("Enter Gateway ID: ");
                        String gatewayId = scanner.nextLine();
                        String registerResponse = grpcClient.registerRoute(deviceId, gatewayId);
                        System.out.println("RegisterRoute Response: " + registerResponse);
                        break;

                    case "get":
                        System.out.print("Enter Device ID: ");
                        deviceId = scanner.nextLine();
                        String getResponse = grpcClient.getRoute(deviceId);
                        System.out.println("GetRoute Response: " + getResponse);
                        break;

                    case "unregister":
                        System.out.print("Enter Device ID: ");
                        deviceId = scanner.nextLine();
                        String unregisterResponse = grpcClient.unregisterRoute(deviceId);
                        System.out.println("UnregisterRoute Response: " + unregisterResponse);
                        break;

                    case "exit":
                        System.out.println("Shutting down...");
                        grpcClient.shutdown(); // 关闭 gRPC 通道
                        return;

                    default:
                        System.out.println("Unknown command. Try again.");
                }
            }
        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
        } finally {
            grpcClient.shutdown(); // 确保在任何异常情况下都能释放资源
        }
    }
}
